package com.fulu.game.bi.service.impl.channel;

import cn.hutool.core.collection.CollectionUtil;
import com.fulu.game.bi.common.exception.BizException;
import com.fulu.game.bi.entity.enums.GroupRelTableEnum;
import com.fulu.game.bi.entity.po.auth.BiUser;
import com.fulu.game.bi.entity.po.channel.GroupRel;
import com.fulu.game.bi.entity.po.channel.Label;
import com.fulu.game.bi.entity.po.channel.LabelGroup;
import com.fulu.game.bi.entity.vo.channel.label.LabelGroupDisplayVO;
import com.fulu.game.bi.entity.vo.channel.label.LabelGroupQueryVO;
import com.fulu.game.bi.entity.vo.channel.label.LabelGroupSaveVO;
import com.fulu.game.bi.enums.CommonlyOrderEnums;
import com.fulu.game.bi.mysql.bi.channel.GroupRelDao;
import com.fulu.game.bi.mysql.bi.channel.LabelGroupDao;
import com.fulu.game.bi.mysql.playadmin.channel.LabelDao;
import com.fulu.game.bi.redis.service.auth.BiUserService;
import com.fulu.game.bi.redis.service.channel.LabelGroupService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LabelGroupServiceImpl implements LabelGroupService {

    @Autowired
    private BiUserService biUserService;

    @Autowired
    private LabelGroupDao labelGroupDao;

    @Autowired
    private LabelDao labelDao;

    @Autowired
    private GroupRelDao groupRelDao;

    @Override
    public LabelGroup save(LabelGroupSaveVO vo) {
        if (Objects.isNull(vo.getId())) {
            return createNewLabelGroup(vo);
        }

        return updateExistLabelGroup(vo);
    }

    private LabelGroup updateExistLabelGroup(LabelGroupSaveVO vo) {
        LabelGroup existGroup = labelGroupDao.findByName(vo.getGroupName());
        if (Objects.nonNull(existGroup) && !existGroup.getId().equals(vo.getId())) {
            throw new BizException("分组名已存在");
        }

        BiUser currentUser = biUserService.getCurrentUser();
        Date now = new Date();

        LabelGroup labelGroup = new LabelGroup();
        BeanUtils.copyProperties(vo, labelGroup);

        labelGroup.setName(vo.getGroupName());
        labelGroup.setUpdateTime(now);
        labelGroup.setUpdateUser(currentUser.getId());

        labelGroupDao.updateSelective(labelGroup);

        log.info("修改标签分组：{}", labelGroupDao);

        return labelGroup;
    }

    private LabelGroup createNewLabelGroup(LabelGroupSaveVO vo) {

        LabelGroup existGroup = labelGroupDao.findByName(vo.getGroupName());
        if (Objects.nonNull(existGroup)) {
            throw new BizException("分组名已存在");
        }

        BiUser currentUser = biUserService.getCurrentUser();
        Date now = new Date();

        LabelGroup labelGroup = new LabelGroup();
        BeanUtils.copyProperties(vo, labelGroup);

        labelGroup.setName(vo.getGroupName());
        labelGroup.setCreateTime(now);
        labelGroup.setUpdateTime(now);
        labelGroup.setCreateUser(currentUser.getId());
        labelGroup.setUpdateUser(currentUser.getId());

        labelGroupDao.insert(labelGroup);

        log.info("新增标签分组：{}", labelGroupDao);

        return labelGroup;

    }

    public void addRel(List<GroupRel> list) {
        groupRelDao.insert(list, GroupRelTableEnum.REGISTER_SOURCE.getName());
    }

    @Override
    public PageInfo<LabelGroupDisplayVO> list(LabelGroupQueryVO vo) {
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize(), CommonlyOrderEnums.UPDATE_DESC.getValue());

        List<LabelGroup> list = labelGroupDao.list(vo);
        PageInfo pageInfo = new PageInfo(list);
        List<LabelGroupDisplayVO> result = list.stream().parallel().map(g -> {
            LabelGroupDisplayVO showVo = new LabelGroupDisplayVO();
            showVo.setId(g.getId());
            showVo.setGroupName(g.getName());
            List<Integer> ids = labelGroupDao.listItem(g.getId());
            showVo.setNum(0);
            showVo.setItemList(Collections.emptyList());
            if (CollectionUtil.isNotEmpty(ids)) {
                List<Label> labels = labelDao.findByIds(ids);
                showVo.setNum(labels.size());
                showVo.setItemList(labels);
            }
            showVo.setAdminId(g.getCreateUser());
            BiUser user = Optional.ofNullable(biUserService.findById(g.getCreateUser())).orElse(new BiUser());
            showVo.setAdminName(user.getName());
            showVo.setCreateTime(g.getCreateTime());
            showVo.setUpdateTime(g.getUpdateTime());
            showVo.setRemark(g.getRemark());
            return showVo;
        }).collect(Collectors.toList());
        pageInfo.setList(result);
        return pageInfo;
    }

    @Override
    public Boolean delete(Integer id) {
        Boolean deleted = false;
        List<Integer> ids = labelGroupDao.listItem(id);
        if (CollectionUtil.isEmpty(ids)) {
            deleted = labelGroupDao.deleteById(id) > 0;
        } else {
            List<Label> labels = labelDao.findByIds(ids);
            if (CollectionUtil.isEmpty(labels)) {
                deleted = labelGroupDao.deleteById(id) > 0 && groupRelDao.deleteByGroupId(id, GroupRelTableEnum.LABEL.getName()) > 0;
            }
        }
        return deleted;
    }
}
